<?php
require_once ZEEGING_PATH."Controllers".DIRECTORY_SEPARATOR.'ApiBaseController.class.php';
require_once ZEEGING_PATH.'Librarys'.DIRECTORY_SEPARATOR.'BOApi.php';
defined('IN_ZEEGING') or die('Access Denied');
class DepositController extends ApiBaseController{
	/*
	CREATE TABLE `deposit` (
	  `amount` float NOT NULL COMMENT '订单金额rmb',
	  `paymentmethod` varchar(50) NOT NULL COMMENT '支付方式',
	  `status` varchar(20) NOT NULL COMMENT '状态0 = inactive, 100 = failed, 200 = completed',
	  `username` int(100) NOT NULL COMMENT '用户唯一标识',
	  `createtime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '订单创建时间',
	  `updatetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后更新时间',
	  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
	  PRIMARY KEY (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='充值订单表'
	*/
	public function xunjieReturnAction(){
		
		$config=$this->loadConfigs('xunjiepay');
		$userkey=$config['userkey'];

		$returnArray = array( // 返回字段
            "memberid" => $this->POST["memberid"], // 商户ID
            "orderid" =>  $this->POST["orderid"], // 订单号
            "amount" =>  $this->POST["amount"], // 交易金额
            "datetime" =>  $this->POST["datetime"], // 交易时间
            "transaction_id" =>  $this->POST["transaction_id"], // 流水号
            "returncode" => $this->POST["returncode"],
            "sign" => $this->POST["sign"];
        );
        ksort($returnArray);
        reset($returnArray);
        $md5str = "";
        foreach ($returnArray as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $mysign = strtoupper(md5($md5str . "key=" . $userkey)); 

		if($returnArray["sign"]==$mysign){
		    if($returnArray["returncode"]=='00'){
		        // echo '付款成功';
		        // 展示成功页
		        $this->assign('amount','￥'.number_format($returnArray["amount"],2,'.',''));
				$this->display('success');
		    } else {
		        // echo 'fail';
		        // 展示失败页
		        $this->assign('orderid',$returnArray["orderid"]);
		        $this->assign('msg','支付过程发生错误，请重试');
				$this->display('failed');
		    }
		} else {
		    // echo 'sign error';
		    // 展示错误页
		    $this->assign('orderid',$returnArray["orderid"]);
	        $this->assign('msg','支付签名错误，请联系客服');
			$this->display('failed');
		}
		
	}
	public function mayaReturnAction(){
		
		$config=$this->loadConfigs('mayapay');
		$userkey=$config['userkey'];
		$status=$this->GET('status');
		$customerid=$this->GET('customerid');
		$sdorderno=$this->GET('sdorderno');
		$total_fee=$this->GET('total_fee');
		$paytype=$this->GET('paytype');
		$sdpayno=$this->GET('sdpayno');
		$remark=$this->GET('remark');
		$sign=$this->GET('sign');

		$mysign=md5('customerid='.$customerid.'&status='.$status.'&sdpayno='.$sdpayno.'&sdorderno='.$sdorderno.'&total_fee='.$total_fee.'&paytype='.$paytype.'&'.$userkey);

		if($sign==$mysign){
		    if($status=='1'){
		        // echo '付款成功';
		        // 展示成功页
		        $this->assign('amount','￥'.number_format($total_fee,2,'.',''));
				$this->display('success');
		    } else {
		        // echo 'fail';
		        // 展示失败页
		        $this->assign('orderid',$sdorderno);
		        $this->assign('msg','支付过程发生错误，请重试');
				$this->display('failed');
		    }
		} else {
		    // echo 'sign error';
		    // 展示错误页
		    $this->assign('orderid',$sdorderno);
	        $this->assign('msg','支付签名错误，请联系客服');
			$this->display('failed');
		}
		
	}
	public function xunjieNotifyAction(){
		
		$requestIP=Base::getUserIP();

		$config=$this->loadConfigs('xunjiepay');
		$userkey=$config['userkey'];

		$returnArray = array( // 返回字段
            "memberid" => $this->POST["memberid"], // 商户ID
            "orderid" =>  $this->POST["orderid"], // 订单号
            "amount" =>  $this->POST["amount"], // 交易金额
            "datetime" =>  $this->POST["datetime"], // 交易时间
            "transaction_id" =>  $this->POST["transaction_id"], // 流水号
            "returncode" => $this->POST["returncode"],
            "sign" => $this->POST["sign"];
        );
        ksort($returnArray);
        reset($returnArray);
        $md5str = "";
        foreach ($returnArray as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $mysign = strtoupper(md5($md5str . "key=" . $userkey)); 

		Base::log("Receive a payment callback from[$requestIP]: status:$returnArray[returncode], customerid:$returnArray[memberid], sdorderno:$returnArray[orderid], total_fee:$returnArray[amount], transcationid:$returnArray[transaction_id], sign:$returnArray[returncode], mysign:$mysign,","DEPOSIT");
		
		if($returnArray["sign"]==$mysign){
		    if($returnArray["returncode"]=='00'){
		    	$boapi=new BOApi();
				$order=$this->loadModel('RealMoneyDepositOrder')->load($returnArray[orderid]);
				if($order->status==0){	// 只有订单状态是0（初始状态），才会给用户加钱，如果订单已经完成（200）或者其他状态，则不会给用户加钱
					// 向后台加钱
					if($boapi->deposit($order->username,$order->amount,BOApi::DEPOSITTYPE_NONWITHDRAWABLE)){
			    		$order->success();
						Base::log("Deposit Success: username: $order->username, amount: $order->amount, method: $order->paymentmethod","DEPOSIT");
						
						// 以下是充值送的逻辑
						$isDepositPromotionEnabling=$this->loadConfigs('base')['DEPOST_PROMOTION'];
						if($isDepositPromotionEnabling){
							try{
								if($order->amount>=10 && $order->amount<100){
									$eachMonthAmountList=[3,3,4];
								}
								else if($order->amount>=100 && $order->amount<1000){
									$eachMonthAmountList=[10,10,10];
								}
								else if($order->amount>=1000){
									$eachMonthAmountList=[50,25,25];
								}
								else{
									$eachMonthAmountList=null;
								}
								if(!empty($eachMonthAmountList)){
									// 即时
									$depositNow=$this->loadModel('DepositTask');
									$depositNow->amount=$eachMonthAmountList[1];
									$depositNow->paymentmethod='ethereum';
									$depositNow->username=$order->username;
									$depositNow->excutiondate=date('Y-m-d');
									$depositNow->save();
									$boapi=new BOApi();
									if($boapi->deposit($depositNow->username,$depositNow->amount,BOApi::DEPOSITTYPE_BONUS)){
										$depositNow->success();
										Base::log("A crontask deposit execute success: orderid: $depositNow->id username: $depositNow->username, amount: $depositNow->amount, executiondate: $depositNow->executiondate",'DEPOST_TASK');
									}
									// 次个月
									$depositTaskNextMonth=$this->loadModel('DepositTask');
									$depositTaskNextMonth->amount=$eachMonthAmountList[1];
									$depositTaskNextMonth->paymentmethod='ethereum';
									$depositTaskNextMonth->username=$order->username;
									$depositTaskNextMonth->excutiondate=DepositTaskModel::nextMonth();
									$depositTaskNextMonth->save();
									// 第三个月
									$depositTaskMonthAfterNextMonth=$this->loadModel('DepositTask');
									$depositTaskMonthAfterNextMonth->amount=$eachMonthAmountList[2];
									$depositTaskMonthAfterNextMonth->paymentmethod='ethereum';
									$depositTaskMonthAfterNextMonth->username=$order->username;
									$depositTaskMonthAfterNextMonth->excutiondate=DepositTaskModel::nextMonth(DepositTaskModel::nextMonth());
									$depositTaskMonthAfterNextMonth->save();
								}
								
							}
							catch(Exception $e){
								Base::log("Some error with saving deposit task: order: id: $order->id, username: $order->username, amount: $order->amount, ErrMsg:".$e,'DEPOST_TASK');
							}
						}
						// 充值送逻辑结束
					}
					else{
			    		Base::log("There are some errors with addding fund by BOApi.","DEPOSIT");
					}
			        echo 'OK';
			    	Base::log("Success.","DEPOSIT");
				}
				else{
					// 订单状态不为0
		        	echo 'fail';
					Base::log("It's a completed/error deposit order(no.: $returnArray[orderid], status: $order->status).","DEPOSIT");
				}
		    } else {
		        echo 'fail';
		    	Base::log("Failed.","DEPOSIT");
		    }
		} else {
		    echo 'signerr';
		    Base::log("Sign error.","DEPOSIT");
		}
		
	}
	public function mayaNotifyAction(){
		
		$config=$this->loadConfigs('mayapay');
		$userkey=$config['userkey'];
		$status=$this->POST('status');
		$customerid=$this->POST('customerid');
		$sdorderno=$this->POST('sdorderno');
		$total_fee=$this->POST('total_fee');
		$paytype=$this->POST('paytype');
		$sdpayno=$this->POST('sdpayno');
		$remark=$this->POST('remark');
		$sign=$this->POST('sign');
		$requestIP=Base::getUserIP();

		$mysign=md5('customerid='.$customerid.'&status='.$status.'&sdpayno='.$sdpayno.'&sdorderno='.$sdorderno.'&total_fee='.$total_fee.'&paytype='.$paytype.'&'.$userkey);
		Base::log("Receive a payment callback from[$requestIP]: status:$status, customerid:$customerid, sdorderno:$sdorderno, total_fee:$total_fee, paytype:$paytype, sdpayno:$sdpayno, remark:$remark, sign:$sign, mysign:$mysign,","DEPOSIT");
		
		if($sign==$mysign){
		    if($status=='1'){
		    	$boapi=new BOApi();
				$order=$this->loadModel('MayaDepositOrder')->load($sdorderno);
				if($order->status==0){	// 只有订单状态是0（初始状态），才会给用户加钱，如果订单已经完成（200）或者其他状态，则不会给用户加钱
					// 向后台加钱
					if($boapi->deposit($order->username,$order->amount,BOApi::DEPOSITTYPE_NONWITHDRAWABLE)){
			    		$order->success();
						Base::log("Deposit Success: username: $order->username, amount: $order->amount, method: $order->paymentmethod","DEPOSIT");
						
						// 以下是充值送的逻辑
						$isDepositPromotionEnabling=$this->loadConfigs('base')['DEPOST_PROMOTION'];
						if($isDepositPromotionEnabling){
							try{
								if($order->amount>=10 && $order->amount<100){
									$eachMonthAmountList=[3,3,4];
								}
								else if($order->amount>=100 && $order->amount<1000){
									$eachMonthAmountList=[10,10,10];
								}
								else if($order->amount>=1000){
									$eachMonthAmountList=[50,25,25];
								}
								else{
									$eachMonthAmountList=null;
								}
								if(!empty($eachMonthAmountList)){
									// 即时
									$depositNow=$this->loadModel('DepositTask');
									$depositNow->amount=$eachMonthAmountList[1];
									$depositNow->paymentmethod='ethereum';
									$depositNow->username=$order->username;
									$depositNow->excutiondate=date('Y-m-d');
									$depositNow->save();
									$boapi=new BOApi();
									if($boapi->deposit($depositNow->username,$depositNow->amount,BOApi::DEPOSITTYPE_BONUS)){
										$depositNow->success();
										Base::log("A crontask deposit execute success: orderid: $depositNow->id username: $depositNow->username, amount: $depositNow->amount, executiondate: $depositNow->executiondate",'DEPOST_TASK');
									}
									// 次个月
									$depositTaskNextMonth=$this->loadModel('DepositTask');
									$depositTaskNextMonth->amount=$eachMonthAmountList[1];
									$depositTaskNextMonth->paymentmethod='ethereum';
									$depositTaskNextMonth->username=$order->username;
									$depositTaskNextMonth->excutiondate=DepositTaskModel::nextMonth();
									$depositTaskNextMonth->save();
									// 第三个月
									$depositTaskMonthAfterNextMonth=$this->loadModel('DepositTask');
									$depositTaskMonthAfterNextMonth->amount=$eachMonthAmountList[2];
									$depositTaskMonthAfterNextMonth->paymentmethod='ethereum';
									$depositTaskMonthAfterNextMonth->username=$order->username;
									$depositTaskMonthAfterNextMonth->excutiondate=DepositTaskModel::nextMonth(DepositTaskModel::nextMonth());
									$depositTaskMonthAfterNextMonth->save();
								}
								
							}
							catch(Exception $e){
								Base::log("Some error with saving deposit task: order: id: $order->id, username: $order->username, amount: $order->amount, ErrMsg:".$e,'DEPOST_TASK');
							}
						}
						// 充值送逻辑结束
					}
					else{
			    		Base::log("There are some errors with addding fund by BOApi.","DEPOSIT");
					}
			        echo 'success';
			    	Base::log("Success.","DEPOSIT");
				}
				else{
					// 订单状态不为0
		        	echo 'fail';
					Base::log("It's a completed/error deposit order(no.: $sdorderno, status: $order->status).","DEPOSIT");
				}
		    } else {
		        echo 'fail';
		    	Base::log("Failed.","DEPOSIT");
		    }
		} else {
		    echo 'signerr';
		    Base::log("Sign error.","DEPOSIT");
		}
		
	}
	public function testAction(){
		$boapi=new BOApi();
		if($boapi->deposit('17665343247','100',BOApi::DEPOSITTYPE_BONUS)){
			// $depositNow->success();
			echo("A crontask deposit execute success");
		}
	    echo("Test log.");
	}
}
//------------------------------------------------
//End of File : /Controllers/IndexController.class.php
//------------------------------------------------
